// axios方法封装
import axios from 'axios';
import api from '../../api/index';

function dataHandler(type,url,data){
    if(!url){
        throw('缺少url');
    }
    if(type === 'get'){
        var query = '';
        if(data){
            query = '?'
            Object.keys(data).forEach(key=> {
                query += `${key}=${data[key]}&`
            })
        }
        url = api.baseUrl + url + query.substring(0,query.length-1);
        return {url}
    }else if(type === 'post'){
        url = api.baseUrl + url;
        return {url,data}
    }
}

class AxiosHandler {
    constructor(baseUrl,timeout){
        this.baseUrl = baseUrl;
        this.timeout = timeout;
        axios.defaults.baseUrl = baseUrl;
        axios.defaults.timeout = timeout;
        axios.interceptors.request.use((config) => {
            //  发送前拦截
            console.log('config=======>',config);
            return config
        },(err) => {
            console.log('err=========>',err)
            return Promise.reject(err);
        })
    }

    get(url,data,header = {}){
        return new Promise((resolved,reject) => {
            axios({
                method:'get',
                ...dataHandler('get',url,data),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8", 
                    // "token":'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOm51bGwsIm5iZiI6MTU4NTcyMjA0MSwiZXhwIjoxNTg1NzY1MjQxLCJ1aWQiOjc2OH0.AEa3Z05U7peD2nJv2wCZj9mB5k9R6tqubGRKCTEBmSw',
                    ...header              
                },
            }).then((res) => {
                if(res.data.code === 1){
                    resolved(res.data);
                }
                // 根据状态码执行
            }).catch(err => {
                reject(err)
            })
        })
    }

    post(url,data,header = {}){
        return new Promise((resolved,reject) => {
            axios({
                method:'post',
                ...dataHandler('post',url,data),
                headers:{
                    "Content-Type": "application/json; charset=UTF-8", 
                    // "token":'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiIiLCJhdWQiOiIiLCJpYXQiOm51bGwsIm5iZiI6MTU4NTcyMjA0MSwiZXhwIjoxNTg1NzY1MjQxLCJ1aWQiOjc2OH0.AEa3Z05U7peD2nJv2wCZj9mB5k9R6tqubGRKCTEBmSw',
                    ...header              
                },
            }).then((res) => {
                if(res.data.code === 1){
                    resolved(res.data);
                }
                // 根据状态码执行
            }).catch(err => {
                reject(err)
            })
        })
    }
}

export default new AxiosHandler(api.baseUrl,1000)